package com.changgou.order.listen;

import com.alibaba.fastjson.JSON;
import com.changgou.order.dao.OrderMapper;
import com.changgou.order.pojo.Order;
import com.rabbitmq.client.Channel;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;

/**
 * 消息队列监听类
 * @author zhengjd
 * @date 2020/5/21 18:10
 */
@SuppressWarnings("SpringJavaInjectionPointsAutowiringInspection")
@Component
@RabbitListener(queues = "queue.order")  //监听队列为queue.order
public class PayOrderUpdateListener {

    @Autowired
    private OrderMapper orderMapper;

    /**
     * //可靠新消息，用于处理queue.order队列的消息
     * @param msg
     */
    @RabbitHandler
    public void handler(Message message, Channel channel, String msg){
        System.out.println(msg);

        //将字符串转化为map
        Map<String,String> map = JSON.parseObject(msg, Map.class);

        if (map != null){
            if ("SUCCESS".equals(map.get("return_code")) && "SUCCESS".equals(map.get("result_code"))){
                //根据订单号获取订单数据
                String out_trade_no = map.get("out_trade_no");
                Order order = orderMapper.selectByPrimaryKey(out_trade_no);
                if (order == null){
                    try {
                        //拒绝签收，不重回队列
                        channel.basicNack(message.getMessageProperties().getDeliveryTag(),false,false);
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                    throw new RuntimeException("该订单不存在！！请重新查询");
                }
                //设置支付完成时间
                String timeEnd = map.get("time_end");
                SimpleDateFormat format = new SimpleDateFormat("yyyyMMddHHmmss");
                Date date = null;
                try {
                    date = format.parse(timeEnd);
                } catch (ParseException e) {
                    e.printStackTrace();
                }
                order.setPayTime(date);
                //设置订单流水号
                order.setTransactionId(map.get("transaction_id"));
                //更新订单
                orderMapper.updateByPrimaryKeySelective(order);
            } else {
                String out_trade_no = map.get("out_trade_no");
                //如果支付出现异常，简单处理，逻辑删除订单
                Order order = orderMapper.selectByPrimaryKey(out_trade_no);
                order.setIsDelete("1");
                orderMapper.updateByPrimaryKeySelective(order);
            }
        }
    }
}
